package xin.nick.demo;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.bouncycastle.asn1.ocsp.ResponseData;

import java.util.Arrays;
import java.util.List;

/**
 * @Auther: Nick inickning@outlook.com
 * @Date: 2021/2/28 13:51
 * @Description:
 */
public class IpFilter extends ZuulFilter {

    // IP黑名单列表
    private List<String> blackIpList = Arrays.asList("127.0.0.1");

    public IpFilter() {
        super();
    }

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        String ip = IpUtils.getIpAddr(ctx.getRequest());
        System.out.println(ip);
        // 在黑名单中禁用
        if (StringUtils.isNotBlank(ip) && blackIpList.contains(ip)) {

            ctx.setSendZuulResponse(false);
            ctx.set("sendForwardFilter.ran", true);
            ctx.set("isSuccess", false);
            ctx.setResponseBody("非法请求");
            System.out.println("非法请求");
            ctx.getResponse().setContentType("application/text; charset=utf-8");

            return null;
        }
        return null;
    }
}
